package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;


/**
 * @author 虎哥
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String UPDATE_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.updateStock";

    @Transactional
    @Override
    public void deductStock(Map<Long, Integer> cartMap) {
        try {
            executeBatch(sqlSession -> {
                for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                    //1. 商品id
                    Long skuId = entry.getKey();
                    //2. 商品数量
                    Integer num = entry.getValue();
                    //4. 扣减库存
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("id", skuId);
                    map.put("num", num);
                    //指定statement的id和对应参数,statementId 就是 mapper的namespace+methodName;
                    sqlSession.update(UPDATE_STOCK_STATEMENT, map);
                }
                //刷新并执行sql
                sqlSession.flushStatements();
            });
        } catch (Exception e) {
            throw new LyException(400, "更新库存失败,库存不足");
        }


    }
}